package com.dianrui.fmi.activity;

import android.support.design.widget.BottomSheetDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.dianrui.fmi.Constant;
import com.dianrui.fmi.R;
import com.dianrui.fmi.util.MyUtil;
import com.dianrui.fmi.util.OkHttpUtils;
import com.dianrui.fmi.util.StringUtils;
import com.dianrui.fmi.util.ToastUtil;
import com.dianrui.fmi.util.Url;
import com.dianrui.fmi.view.pulltoRefresh.PullToRefreshBase;
import com.dianrui.fmi.view.pulltoRefresh.PullToRefreshListView;
import com.dianrui.fmi.view.wheelviews.wheelview.OnItemSelectedListener;
import com.dianrui.fmi.view.wheelviews.wheelview.WheelView;
import com.google.gson.JsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 *
 */

public class TransactionRecordActivity extends BaseActivity {
    private int mPageIndex = 1;
    private List<String> years = new ArrayList<>();
    private List<String> months = new ArrayList<>();
    private List<String> days = new ArrayList<>();

    private static int MIN_YEAR = 2020;
    private static int MAX_YEAR = 2200;

    private int yearPos;
    private int monthPos;
    private int dayPos;

    private WheelView mYearWheelView;
    private WheelView mMonthWheelView;
    private WheelView mDayWheelView;
    private OnDateCListener mOnDateCListener;

    @BindView(R.id.title)
    TextView title;
    TextView startTime;
    TextView endTime;
    @BindView(R.id.tr_listview)
    PullToRefreshListView trListview;
    @BindView(R.id.right_img)
    ImageView rightImg;
    @BindView(R.id.emptyView)
    LinearLayout EmptyView;


    @Override
    public int getContentViewId() {
        return R.layout.activity_transaction_record;
    }

    @Override
    public void initView() {
        title.setText(getString(R.string.deal_record));
        rightImg.setImageResource(R.mipmap.caldanar_img);
        rightImg.setVisibility(View.VISIBLE);
        getTranscationRecord(false);
        trListview.setMode(PullToRefreshBase.Mode.BOTH);
        trListview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                getTranscationRecord(true);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                mPageIndex++;
                getTranscationRecord(false);

            }
        });
    }

    private void getTranscationRecord(final boolean isRfresh) {
        if (isRfresh) {
            mPageIndex = 1;
        }
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("is_real", "1");
        jsonObject.addProperty("p", mPageIndex);
        OkHttpUtils.getInstance().postWithMemberToken(Url.FINANCE, jsonObject.toString(), new OkHttpUtils.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (trListview != null) {
                    trListview.onRefreshComplete();
                }
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject &&!isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                JSONArray jsonArray = jsonObject.optJSONArray("data");
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {

                                    }
                                    EmptyView.setVisibility(View.GONE);
                                    trListview.setVisibility(View.VISIBLE);
                                }else {
                                    EmptyView.setVisibility(View.VISIBLE);
                                    trListview.setVisibility(View.INVISIBLE);

                                }

                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                } else {
                    if (trListview != null) {
                        trListview.onRefreshComplete();
                    }
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }
        });
    }


    @OnClick({R.id.back, R.id.transaction_type_layout,R.id.right_img})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.transaction_type_layout:
                break;

            case R.id.right_img:
                final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(TransactionRecordActivity.this);
                View view2 = LayoutInflater.from(TransactionRecordActivity.this).inflate(R.layout.dialog_choose_date, null);
                mYearWheelView = view2.findViewById(R.id.wv_province);
                mMonthWheelView = view2.findViewById(R.id.wv_city);
                mDayWheelView = view2.findViewById(R.id.wv_district);
                 startTime = view2.findViewById(R.id.dialog_start_time);
                 endTime = view2.findViewById(R.id.dialog_end_time);
                LinearLayout starttimeLayout= view2.findViewById(R.id.start_time_layout);
                LinearLayout endtimeLayout= view2.findViewById(R.id.end_time_layout);
                Button cancel = view2.findViewById(R.id.cancel);
                Button ok = view2.findViewById(R.id.ok);
                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bottomSheetDialog.dismiss();
                    }
                });

                ok.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bottomSheetDialog.dismiss();
                    }
                });
                SimpleDateFormat myFmt = new SimpleDateFormat("yyyy-MM-dd");
                Date now = new Date();
                startTime.setText(myFmt.format(now));
                endTime.setText(myFmt.format(now));
                initData();
                setListener();

                mYearWheelView.setVisibleItemCount(9);
                mMonthWheelView.setVisibleItemCount(9);
                mDayWheelView.setVisibleItemCount(9);

                mYearWheelView.isCenterLabel(true);
                mMonthWheelView.isCenterLabel(true);
                mDayWheelView.isCenterLabel(true);



                mYearWheelView.setOnItemSelectedListener(new OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(int index) {
                        int currentItem = mDayWheelView.getCurrentItem();
                        currentItem = currentItem >= days.size() - 1 ? days.size() - 1 : currentItem;
                        startTime.setText(years.get(mYearWheelView.getCurrentItem())+"-"+months.get(mMonthWheelView.getCurrentItem())+"-"+days.get(currentItem));




                    }
                });
                mMonthWheelView.setOnItemSelectedListener(new OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(int index) {
                        int currentItem = mDayWheelView.getCurrentItem();
                        currentItem = currentItem >= days.size() - 1 ? days.size() - 1 : currentItem;
                        startTime.setText(years.get(mYearWheelView.getCurrentItem())+"-"+months.get(mMonthWheelView.getCurrentItem())+"-"+days.get(currentItem));




                    }
                });

                mDayWheelView.setOnItemSelectedListener(new OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(int index) {
                        int currentItem = mDayWheelView.getCurrentItem();
                        currentItem = currentItem >= days.size() - 1 ? days.size() - 1 : currentItem;
                        startTime.setText(years.get(mYearWheelView.getCurrentItem())+"-"+months.get(mMonthWheelView.getCurrentItem())+"-"+days.get(currentItem));
                    }
                });
                bottomSheetDialog.setContentView(view2);
                bottomSheetDialog.setCancelable(false);
                bottomSheetDialog.setCanceledOnTouchOutside(false);
                if (!MyUtil.getActivity(bottomSheetDialog.getContext()).isFinishing()) {
                    bottomSheetDialog.show();
                }
                break;

                default:
                    break;
        }
    }

    private void initData() {

        Calendar nowCalendar = Calendar.getInstance();
        yearPos = nowCalendar.get(Calendar.YEAR) - MIN_YEAR;
        monthPos = nowCalendar.get(Calendar.MONTH);
        dayPos = nowCalendar.get(Calendar.DAY_OF_MONTH) - 1;

        //初始化年
        for (int i = 0; i <= MAX_YEAR - MIN_YEAR; i++) {
            years.add(format(MIN_YEAR + i));
        }
        mYearWheelView.setItems(years);
        mYearWheelView.setCurrentItem(yearPos);
        //初始化月
        for (int i = 0; i < 12; i++) {
            months.add(format(i + 1));
        }
        mMonthWheelView.setItems(months);
        mMonthWheelView.setCurrentItem(monthPos);

        //设置日
        setDay();
    }
    private void setListener() {
        //年份*****************************
        mYearWheelView.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                yearPos = index;
                //设置日
                setDay();
            }
        });
        //月份********************
        mMonthWheelView.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                monthPos = index;
                //设置日
                setDay();
            }
        });
        //日********************
        mDayWheelView.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                dayPos = index;
            }
        });


    }

    /**
     * 回调接口
     */
    public interface OnDateCListener {
        void onDateSelected(String year, String month, String day);
    }

    public void setDateListener(OnDateCListener mOnDateCListener) {
        this.mOnDateCListener = mOnDateCListener;
    }

    /**
     * 设置日
     */
    private void setDay() {
        if (years != null && months != null && days != null) {
            boolean isRun = isRunNian(Integer.parseInt(years.get(yearPos)));
            int dayCount = 0;
            switch (Integer.parseInt(months.get(monthPos))) {
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                    dayCount = 31;
                    break;
                case 2:
                    if (isRun) {
                        dayCount = 29;
                    } else {
                        dayCount = 28;
                    }
                    break;
                case 4:
                case 6:
                case 9:
                case 11:
                    dayCount = 30;
                    break;
            }
            days.clear();
            for (int i = 0; i < dayCount; i++) {
                days.add(format(i + 1));
            }

            mDayWheelView.setItems(days);
            dayPos = dayPos >= days.size() - 1 ? days.size() - 1 : dayPos;
            mDayWheelView.setCurrentItem(dayPos);
        }
    }

    /**
     * 判断是否是闰年
     * @param year
     * @return
     */
    private boolean isRunNian(int year) {
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
            return true;
        } else {
            return false;
        }
    }

    private String format(int num) {
        return (num < 10) ? "0" + num : String.valueOf(num);
    }
}
